<template>
    <div class="login">
        <video class="videoBox" autoplay loop muted>
            <source src="/images/login/loginVideo.mp4" type="video/mp4" />
        </video>
        <div class="content">
            <h3><img src="/images/login/组3.png" alt="" /></h3>
            <el-form ref="loginForm" :model="form" :rules="rules" >
                <el-form-item prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名">
                        <template v-slot:prefix>
                            <i>
                                <img src="/images/login/user.png" alt />
                            </i>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password" >
                    <el-input
                        type="password"
                        v-model="form.password"
                        placeholder="请输入密码"
                    >
                        <template v-slot:prefix>
                            <i>
                                <img src="/images/login/pass.png" alt />
                            </i>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="validCode" class="verify" v-if="imgUrl">
                    <div >
                        <el-input
                            type="text"
                            v-model="form.validCode"
                            placeholder="请输入图片中的验证码"
                        >
                        </el-input>
                        <img :src="imgUrl" />
                    </div>
                </el-form-item>
            </el-form>
            <p @click="submit">登录</p>
        </div>
        <div class="footer">&copy;中科星图股份有限公司</div>
        
    </div>
</template>

<script>
// import { login } from '@/api/hainanApi'
import { ElMessage } from 'element-plus'
import axios from "axios";
const http = axios.create({
    baseURL: window.mhLoginUrl,
    timeout: 1000 * 60,
    withCredentials: true,
});
/**
 * 请求拦截
 */
http.interceptors.request.use(
    (config) => {
        config.headers["Authorization"] =
            localStorage.getItem("Authorization") || null;
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default {
    name: "login",
    data() {
        var validateName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入账号'));
            }else{
                callback()
            }
        };

        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            }else{
                callback()
            }
        };
        
        var validateVeri = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入验证码'));
            }else{
                callback()
            }
        };
        return {
            //baisha_t
            //baisha_t123
            form:{
                password: "",
                username: "",
                validCode:''
            },
            countDown:0,
            isErrorLogin: false,
            imgUrl: null,
            yzm: "",
            // 表单验证，需要在 el-form-item 元素中增加 prop 属性
            rules: {
                username: [
                    {required: true, validator: validateName, trigger: 'blur'}
                ],
                password: [
                    {required: true, validator: validatePass, trigger: 'blur'}
                ],
                validCode: [
                    {required: true, validator: validateVeri, trigger: 'blur'}
                ]
            },
            
        };
    },
    created(){
        document.onkeydown =  (e)=> {
            let key = window.event.keyCode;
            if (key === 13) {
                this.onSubmit('loginForm')
            }
        };
    },
    mounted() {
        //this.changeImg();
        //   if(this.$route.query.message){
        //     this.$message(this.$route.query.message)
        //   }
        // console.log(localStorage.getItem('FireAuth'))
        // axios.post("https://gateway.tq-service.com/tqdata/video/listUrl",{projectId:"97d347c331f34e4a91acc7a90c5795a3",startTimeStr:"2021-05-07"}).then((res)=>{
        //         console.log(res)
        //     })
        //     axios.post("http://bh3a.tq-service.com/api/deviceinfo/hlsUrl",{projectId:"cee84d12-eb5e-4883-b189-ba35a218bb4b"}).then((res)=>{
        //         console.log(res)
        //     })
    },
    methods: {
        // 登录
        login(query) {
            return http({
                url: "/api/login",
                method: "post",
                data: query,
            });
        },
        // 判断是否需要验证码
        judgeCode() {
            return http({
                url: "/api/login/needValid",
                method: "get",
            });
        },
        // 请求图片
        getImg() {
            return http({
                url: "/api/login/render",
                method: "get",
                responseType: "blob", //设定接收类型为blob,头部什么的自行添加
            });
        },
        // 更换验证码图片
        async changeImg() {
            // 3次失败加载验证码
            // 5次锁定账号，锁6分钟
            // 一，判断是否需要验证码
            let codeRes = await this.judgeCode();
            if (codeRes.data.status === 200) {//不需要
                this.imgUrl = null;
            } else if (codeRes.data.status === 40121) {//需要
                localStorage.setItem(
                    "Authorization",
                    codeRes.data.data.tokenAuth
                );
                let imgRes = await this.getImg();
                this.imgUrl = URL.createObjectURL(imgRes.data);
            }
        },
        // export function login(params){
        //   return request({
        //     url:"/api/singleLogin",
        //     method:"post",
        //     params:params
        //   })
        // }
        areaCut(data) {
            let arr = data.split('/').slice(1);
            let result = arr.filter((item)=>{
                return item !="";
            })
            return result;
        },
        onSubmit(formName) {
            let that = this;
            // 为表单绑定验证功能
            that.$refs[formName].validate((valid) => {
                if (valid) {
                    that.countDown = 5;
                    let timeId = setInterval(()=>{
                        if(that.countDown === 1) clearInterval(timeId)
                        that.countDown--
                    },1000)
                    let md5Pass = md5(md5(that.form.username + that.form.password) + that.form.username)
                    let type  = null;
                    let uri = null;
                    if(window.isOnline){
                        type = 'OUT'
                        // uri = "/judge?page=/fxfk"
                    }else{
                        type = "IN"
                        // uri = window.location.origin + "/fxfk"
                    }
                    let routeParams = {
                        appNetType: type,
                        jwtType: "CODE" ,
                        // redirectUri:uri ,
                        taiId: 1//可视化系统id
                    }
                    let formData = {
                        jwtToken: routeParams,
                        username: that.form.username,
                        password: md5Pass,
                        validCode: that.form.validCode
                    }
                    this.login(formData).then(res=>{
                        res.data.data.tokenAuth && localStorage.setItem('Authorization', res.data.data.tokenAuth);
                        
                        axios.get(`${sjzxUrl}/api/jwtUser`,{
                            headers:{
                                Authorization: localStorage.Authorization
                            }
                        }).then((res)=>{
                            let tuRegion = that.areaCut(res.data.tuRegion);
                            let region = '';
                            if(tuRegion.length==1){
                                region = tuRegion[0]
                            }else{
                                region = tuRegion[1]
                            }
                            let depart = '';
                            let thDepart = res.data.tudNames;
                            if(thDepart==="海南省"){
                                depart = "海南省"
                            }else{
                                let thDepart1 = that.areaCut(res.data.tudNames);
                                depart = thDepart1[thDepart1.length-1];
                            }
                            that.$message({
                                message: '登陆成功',
                                type: 'success'
                            });
                            that.$store.commit('changeUserName',res.data.tuNickname)
                            that.$store.commit('changeUserRegion',region)
                            that.$store.commit('changeUserDepart',depart)
                            that.$router.push({name:'fxfk'})
                        })
                        //res.data.redirectUrl ? window.location.href = res.data.redirectUrl : 
                        
                    }).catch(err=>{
                        that.$message(err.response.message)
                        that.changeImg()
                    })
                } else {
                    that.dialogVisible = true;
                    return false;
                }
            });
        },
        checkInput() {
            if (!this.username) {
                this.$message({
                    type: "error",
                    message: "请输入用户名",
                });
                return false;
            } else if (!this.password) {
                this.$message({
                    type: "error",
                    message: "请输入密码",
                });
                return false;
            } else {
                return true;
            }
        },
        submit() {
            this.onSubmit("loginForm")
            return;
            if (this.checkInput()) {
                let name = this.username;
                let password = this.password;
                let pwHash = md5(password + name);
                let params = {
                    username: name,
                    password: pwHash,
                };
                // let res = await login(params)
                // user:wuzhanchao_t
                // password:hiko@123456wuzhanchao_t
                axios
                    .post(
                        window.loginUrl + "/api/singleLogin",
                        {},
                        {
                            params: {
                                username: params.username,
                                password: params.password,
                            },
                        }
                    )
                    .then((res) => {
                        console.log(res);
                        if (res.data) {
                            let date = new Date();
                            localStorage.setItem("VisAuth", date.getTime());
                            this.$store.commit("changeVisAuth", date.getTime());
                            this.$router.push("/fxfk");
                        } else {
                            this.$message({
                                type: "error",
                                message: "账号或密码错误",
                            });
                        }
                    });
            }
        },
    },
};
</script>

<style lang="stylus">
.el-message{
    p{
        color:#000!important;
    }
}
.login {
    .el-input {
        height: vh(40);

        input {
            height: vh(40);
        }
    }

    .el-input__prefix {
        margin-top: 5px;

        img {
            width: vw(30);
            height: vh(30);
        }
    }

    .el-input--prefix .el-input__inner {
        padding-left: vw(35);
        line-height: vh(40);
        font-size: vw(16);
        width:vw(300)
    }
}
</style>
<style lang="stylus" scoped>
@media (max-width: 2880px) {
    .login {
        .videoBox {
            position: fixed;
            left: 0;
            top: 0;
            width: 100vw;
            z-index: 20;
        }

        .content {
            position: fixed;
            z-index: 20;
            left: 0;
            right: 0;
            top: vh(200);
            bottom: 0;
            margin: auto;
            // width: 873px;
            // height:627px;
            width: vw(873);
            height: vh(627);
            background: url('/images/login/panel.png') no-repeat;
            background-size: 100% 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            h3 {
                position: absolute;
                top: -100px;
                // left:140px;
                transform: scale(2);

                img {
                    width: 100%;
                }
            }

            .el-input {
                width: 40%;
                background: #36839b;
            }

            .el-input:nth-of-type(2) {
                margin: 30px;
            }

            p {
                width: 40%;
                height: vh(40);
                line-height: vh(40);
                background: #17d0ff;
                text-align: center;
                font-size: vw(20);
                color: #1b1b1b;
                cursor: pointer;
                position: relative;
                z-index: 4;
            }
        }

        .footer {
            position: fixed;
            z-index: 3;
            left: 0;
            right: 0;
            bottom: 30px;
            margin: auto;
            color: rgba(4, 185, 205, 0.3);
        }

        .logo {
            position: fixed;
            left: 30px;
            top: 30px;
            z-index: 3;
        }
    }
}

@media (min-width: 3000px) {
    .login {
        width: 100vw;

        .videoBox {
            position: fixed;
            left: 0;
            top: vh(-400);
            width: 100vw;
            z-index: 20;
        }

        .content {
            position: fixed;
            z-index: 20;
            left: 0;
            right: 0;
            top: vh(200);
            bottom: 0;
            margin: auto;
            // width: 873px;
            // height:627px;
            width: vw1(873);
            height: vh(627);
            background: url('/images/login/panel.png') no-repeat;
            background-size: 100% 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            h3 {
                position: absolute;
                top: -100px;
                // left:140px;
                transform: scale(2);

                img {
                    width: 100%;
                }
            }

            .el-input {
                width: 40%;
                background: #36839b;
            }

            .el-input:nth-of-type(2) {
                margin: 30px;
            }

            p {
                width: 40%;
                height: vh(40);
                line-height: vh(40);
                background: #17d0ff;
                text-align: center;
                font-size: vw1(22);
                color: #1b1b1b;
                cursor: pointer;
                position: relative;
                z-index: 4;
            }
        }

        .footer {
            position: fixed;
            z-index: 3;
            left: 0;
            right: 0;
            bottom: 30px;
            margin: auto;
            color: rgba(4, 185, 205, 0.3);
        }

        .logo {
            position: fixed;
            left: 30px;
            top: 30px;
            z-index: 3;
        }
    }
}
</style>